<!DOCTYPE html>












  


<html class="theme-next mist use-motion" lang="zh-CN">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
































<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=6.6.0" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=6.6.0">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/avatar.jpg?v=6.6.0">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/avatar.jpg?v=6.6.0">


  <link rel="mask-icon" href="/images/logo.svg?v=6.6.0" color="#222">









<script id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Mist',
    version: '6.6.0',
    sidebar: {"position":"left","display":"hide","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: false,
    fastclick: false,
    lazyload: false,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>


  




  <meta name="description" content="说到数据库连接池，就不得不说到Hikari这位后起之秀，号称目前最快的数据库连接池，已成为Spring Boot默认的数据库连接池。 最近得空，想好好写一下之前对源码的总结，包括以前看源码的时候没有理解到位的地方再好好斟酌一下。 文本所采用的版本是当前最新版本 HikariCP-3.3.1，尽量能够解读全面，也希望大家能反馈和理解表述错误或不合理的地方。 核心并发管理ConcurrentBag这个">
<meta name="keywords" content="源码分析,HikariCP,并发">
<meta property="og:type" content="article">
<meta property="og:title" content="HikariCP源码深度解读（一）">
<meta property="og:url" content="http://yoursite.com/2019/03/19/HikariCP源码深度解读（一）/index.html">
<meta property="og:site_name" content="isunimp">
<meta property="og:description" content="说到数据库连接池，就不得不说到Hikari这位后起之秀，号称目前最快的数据库连接池，已成为Spring Boot默认的数据库连接池。 最近得空，想好好写一下之前对源码的总结，包括以前看源码的时候没有理解到位的地方再好好斟酌一下。 文本所采用的版本是当前最新版本 HikariCP-3.3.1，尽量能够解读全面，也希望大家能反馈和理解表述错误或不合理的地方。 核心并发管理ConcurrentBag这个">
<meta property="og:locale" content="zh-CN">
<meta property="og:updated_time" content="2019-04-11T13:50:09.419Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="HikariCP源码深度解读（一）">
<meta name="twitter:description" content="说到数据库连接池，就不得不说到Hikari这位后起之秀，号称目前最快的数据库连接池，已成为Spring Boot默认的数据库连接池。 最近得空，想好好写一下之前对源码的总结，包括以前看源码的时候没有理解到位的地方再好好斟酌一下。 文本所采用的版本是当前最新版本 HikariCP-3.3.1，尽量能够解读全面，也希望大家能反馈和理解表述错误或不合理的地方。 核心并发管理ConcurrentBag这个">






  <link rel="canonical" href="http://yoursite.com/2019/03/19/HikariCP源码深度解读（一）/">



<script id="page.configurations">
  CONFIG.page = {
    sidebar: "",
  };
</script>

  <title>HikariCP源码深度解读（一） | isunimp</title>
  












  <noscript>
  <style>
    .use-motion .motion-element,
    .use-motion .brand,
    .use-motion .menu-item,
    .sidebar-inner,
    .use-motion .post-block,
    .use-motion .pagination,
    .use-motion .comments,
    .use-motion .post-header,
    .use-motion .post-body,
    .use-motion .collection-title { opacity: initial; }

    .use-motion .logo,
    .use-motion .site-title,
    .use-motion .site-subtitle {
      opacity: initial;
      top: initial;
    }

    .use-motion .logo-line-before i { left: initial; }
    .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope="" itemtype="http://schema.org/WebPage" lang="zh-CN">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope="" itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">isunimp</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
    
      
        <p class="site-subtitle">isunimp</p>
      
    
  </div>

  <div class="site-nav-toggle">
    <button aria-label="切换导航栏">
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>



<nav class="site-nav">
  
    <ul id="menu" class="menu">
      
        
        
        
          
          <li class="menu-item menu-item-home">

    
    
    
      
    

    

    <a href="/" rel="section"><i class="menu-item-icon fa fa-fw fa-home"></i> <br>首页</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-archives">

    
    
    
      
    

    

    <a href="/archives/" rel="section"><i class="menu-item-icon fa fa-fw fa-archive"></i> <br>归档</a>

  </li>
        
        
        
          
          <li class="menu-item menu-item-about">

    
    
    
      
    

    

    <a href="/about/" rel="section"><i class="menu-item-icon fa fa-fw fa-user"></i> <br>关于</a>

  </li>

      
      
    </ul>
  

  
    

  

  
</nav>



  



</div>
    </header>

    


    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  

  <article class="post post-type-normal" itemscope="" itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/2019/03/19/HikariCP源码深度解读（一）/">

    <span hidden itemprop="author" itemscope="" itemtype="http://schema.org/Person">
      <meta itemprop="name" content="isunimp">
      <meta itemprop="description" content="涉猎广泛，不亦乐乎，不求甚解。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope="" itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="isunimp">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">HikariCP源码深度解读（一）

              
            
          </h1>
        

        <div class="post-meta">
          <span class="post-time">

            
            
            

            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              

              
                
              

              <time title="创建时间：2019-03-19 16:45:20" itemprop="dateCreated datePublished" datetime="2019-03-19T16:45:20+08:00">2019-03-19</time>
            

            
              

              
                
                <span class="post-meta-divider">|</span>
                

                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                
                  <span class="post-meta-item-text">更新于</span>
                
                <time title="修改时间：2019-04-11 21:50:09" itemprop="dateModified" datetime="2019-04-11T21:50:09+08:00">2019-04-11</time>
              
            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope="" itemtype="http://schema.org/Thing"><a href="/categories/HikariCP/" itemprop="url" rel="index"><span itemprop="name">HikariCP</span></a></span>

                
                
              
            </span>
          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>说到数据库连接池，就不得不说到<code>Hikari</code>这位后起之秀，号称目前最快的数据库连接池，已成为<code>Spring Boot</code>默认的数据库连接池。</p>
<p>最近得空，想好好写一下之前对源码的总结，包括以前看源码的时候没有理解到位的地方再好好斟酌一下。</p>
<p>文本所采用的版本是当前最新版本 <a href="https://github.com/brettwooldridge/HikariCP/tree/HikariCP-3.3.1" target="_blank" rel="noopener">HikariCP-3.3.1</a>，尽量能够解读全面，也希望大家能反馈和理解表述错误或不合理的地方。</p>
<h4 id="核心并发管理"><a href="#核心并发管理" class="headerlink" title="核心并发管理"></a>核心并发管理</h4><p><code>ConcurrentBag</code>这个类可以说是 HikariCP 的最核心了，相当于<code>AbstractQueuedSynchronizer</code>之于<code>ReentrantLock</code>，它提供了对连接最基本的并发管理。</p>
<p>先来看看有哪些属性，搞清楚这些基本就知道作者是什么套路了，毕竟可以猜嘛！</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 共享列表，用于存储连接</span></span><br><span class="line"><span class="comment">// 连接池这种场景写少读多，使用 CopyOnWriteArrayList 并发性很好</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> CopyOnWriteArrayList&lt;T&gt; sharedList;</span><br><span class="line"><span class="comment">// 标识是否使用弱引用</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="keyword">boolean</span> weakThreadLocals;</span><br><span class="line"><span class="comment">// 线程列表，为了避免强烈的连接竞争，将连接缓存在线程内部</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> ThreadLocal&lt;List&lt;Object&gt;&gt; threadList;</span><br><span class="line"><span class="comment">// 通知外部需要新增连接</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> IBagStateListener listener;</span><br><span class="line"><span class="comment">// 等待数量</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> AtomicInteger waiters;</span><br><span class="line"><span class="comment">// 标识是否已关闭</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">volatile</span> <span class="keyword">boolean</span> closed;</span><br><span class="line"><span class="comment">// 传递连接的队列</span></span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> SynchronousQueue&lt;T&gt; handoffQueue;</span><br></pre></td></tr></table></figure>
<p>了解了基本属性，看看构造方法</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ConcurrentBag</span><span class="params">(<span class="keyword">final</span> IBagStateListener listener)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 监听器由外部传入</span></span><br><span class="line">   <span class="keyword">this</span>.listener = listener;</span><br><span class="line">   <span class="comment">// 当用户自定义了类加载时，该值为true，默认为false，也可以由用户指定</span></span><br><span class="line">   <span class="keyword">this</span>.weakThreadLocals = useWeakThreadLocals();</span><br><span class="line"></span><br><span class="line">   <span class="keyword">this</span>.handoffQueue = <span class="keyword">new</span> SynchronousQueue&lt;&gt;(<span class="keyword">true</span>);</span><br><span class="line">   <span class="keyword">this</span>.waiters = <span class="keyword">new</span> AtomicInteger();</span><br><span class="line">   <span class="keyword">this</span>.sharedList = <span class="keyword">new</span> CopyOnWriteArrayList&lt;&gt;();</span><br><span class="line">   <span class="keyword">if</span> (weakThreadLocals) &#123;</span><br><span class="line">      <span class="keyword">this</span>.threadList = ThreadLocal.withInitial(() -&gt; <span class="keyword">new</span> ArrayList&lt;&gt;(<span class="number">16</span>));</span><br><span class="line">   &#125;</span><br><span class="line">   <span class="keyword">else</span> &#123;</span><br><span class="line">       <span class="comment">// 作者自定义了 List，只实现了add、remove等几个必要的方法，源码比较简单，就不单独说了</span></span><br><span class="line">       <span class="comment">// 主要优化了添加元素时不进行 rangeCheck，移除元素时从后向前扫描</span></span><br><span class="line">      <span class="keyword">this</span>.threadList = ThreadLocal.withInitial(() -&gt; <span class="keyword">new</span> FastList&lt;&gt;(IConcurrentBagEntry.class, <span class="number">16</span>));</span><br><span class="line">   &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>管理的元素类型是 <code>IConcurrentBagEntry</code> 接口，ConcurrentBag 的内部接口，包含了4种状态，获取、设置以及 CAS 设置状态。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">interface</span> <span class="title">IConcurrentBagEntry</span></span></span><br><span class="line"><span class="class"></span>&#123;</span><br><span class="line">  <span class="keyword">int</span> STATE_NOT_IN_USE = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">int</span> STATE_IN_USE = <span class="number">1</span>;</span><br><span class="line">  <span class="keyword">int</span> STATE_REMOVED = -<span class="number">1</span>;</span><br><span class="line">  <span class="keyword">int</span> STATE_RESERVED = -<span class="number">2</span>;</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">boolean</span> <span class="title">compareAndSet</span><span class="params">(<span class="keyword">int</span> expectState, <span class="keyword">int</span> newState)</span></span>;</span><br><span class="line">  <span class="function"><span class="keyword">void</span> <span class="title">setState</span><span class="params">(<span class="keyword">int</span> newState)</span></span>;</span><br><span class="line">  <span class="function"><span class="keyword">int</span> <span class="title">getState</span><span class="params">()</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<h5 id="获取连接"><a href="#获取连接" class="headerlink" title="获取连接"></a>获取连接</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> T <span class="title">borrow</span><span class="params">(<span class="keyword">long</span> timeout, <span class="keyword">final</span> TimeUnit timeUnit)</span> <span class="keyword">throws</span> InterruptedException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">   <span class="comment">// 首先从线程队列获取</span></span><br><span class="line">    <span class="keyword">final</span> List&lt;Object&gt; list = threadList.get();</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = list.size() - <span class="number">1</span>; i &gt;= <span class="number">0</span>; i--) &#123;</span><br><span class="line">        <span class="keyword">final</span> Object entry = list.remove(i);</span><br><span class="line">        <span class="meta">@SuppressWarnings</span>(<span class="string">"unchecked"</span>)</span><br><span class="line">        <span class="keyword">final</span> T bagEntry = weakThreadLocals ? ((WeakReference&lt;T&gt;) entry).get() : (T) entry;</span><br><span class="line">        <span class="comment">// 线程队列不为空则尝试 CAS 修改状态</span></span><br><span class="line">        <span class="keyword">if</span> (bagEntry != <span class="keyword">null</span> &amp;&amp; bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) &#123;</span><br><span class="line">            <span class="comment">// 修改成功则表示抢占连接成功</span></span><br><span class="line">            <span class="keyword">return</span> bagEntry;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 代码走到这儿说明线程队列没有连接或所有连接都正在被使用，等待数量 +1</span></span><br><span class="line">    <span class="keyword">final</span> <span class="keyword">int</span> waiting = waiters.incrementAndGet();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        <span class="comment">// 从共享队列获取</span></span><br><span class="line">        <span class="keyword">for</span> (T bagEntry : sharedList) &#123;</span><br><span class="line">            <span class="comment">// 老规矩，CAS 修改状态</span></span><br><span class="line">            <span class="keyword">if</span> (bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) &#123;</span><br><span class="line">                <span class="comment">// 获取成功</span></span><br><span class="line">                <span class="keyword">if</span> (waiting &gt; <span class="number">1</span>) &#123;</span><br><span class="line">                    <span class="comment">// 获取成功但此时等待数量大于1，表示当前连接不够用，需要通知外部创建连接</span></span><br><span class="line">                    <span class="comment">// 为什么是大于 1，因为该线程在95行自增后，此时还没有 -1</span></span><br><span class="line">                    listener.addBagItem(waiting - <span class="number">1</span>);</span><br><span class="line">                &#125;</span><br><span class="line">                <span class="keyword">return</span> bagEntry;</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        </span><br><span class="line">        <span class="comment">// 代码到这儿说明共享队列也没有空闲连接，通知外部创建连接</span></span><br><span class="line">        listener.addBagItem(waiting);</span><br><span class="line">        </span><br><span class="line">        timeout = timeUnit.toNanos(timeout);</span><br><span class="line">        <span class="keyword">do</span> &#123;</span><br><span class="line">            <span class="keyword">final</span> <span class="keyword">long</span> start = currentTime();</span><br><span class="line">            <span class="comment">// 阻塞等待连接释放或新增</span></span><br><span class="line">            <span class="keyword">final</span> T bagEntry = handoffQueue.poll(timeout, NANOSECONDS);</span><br><span class="line">            <span class="comment">// CAS 抢占</span></span><br><span class="line">            <span class="comment">// 为什么需要 CAS 抢占状态而不是直接使用？</span></span><br><span class="line">            <span class="comment">// 因为添加连接的时候会先把连接放到共享队列，再放到handoffQueue，放到共享队列时有可能刚好被其他线程抢占成功</span></span><br><span class="line">            <span class="keyword">if</span> (bagEntry == <span class="keyword">null</span> || bagEntry.compareAndSet(STATE_NOT_IN_USE, STATE_IN_USE)) &#123;</span><br><span class="line">                <span class="keyword">return</span> bagEntry;</span><br><span class="line">            &#125;</span><br><span class="line"></span><br><span class="line">            timeout -= elapsedNanos(start);</span><br><span class="line">        &#125; <span class="keyword">while</span> (timeout &gt; <span class="number">10_000</span>);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">finally</span> &#123;</span><br><span class="line">        <span class="comment">// 获取到连接了，等待数量 -1</span></span><br><span class="line">        waiters.decrementAndGet();</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="释放连接到连接池"><a href="#释放连接到连接池" class="headerlink" title="释放连接到连接池"></a>释放连接到连接池</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requite</span><span class="params">(<span class="keyword">final</span> T bagEntry)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">    <span class="comment">// 直接将状态设置为空闲状态</span></span><br><span class="line">    bagEntry.setState(STATE_NOT_IN_USE);</span><br><span class="line"></span><br><span class="line">    <span class="comment">// 轮询等待数量 &gt; 0</span></span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">0</span>; waiters.get() &gt; <span class="number">0</span>; i++) &#123;</span><br><span class="line">        <span class="comment">// 如果释放的连接还没有被其他线程占用，则检查handoffQueue是否有正在等待的线程</span></span><br><span class="line">        <span class="keyword">if</span> (bagEntry.getState() != STATE_NOT_IN_USE || handoffQueue.offer(bagEntry)) &#123;</span><br><span class="line">            <span class="keyword">return</span>;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">// 每轮询256次，阻塞 10 微妙</span></span><br><span class="line">        <span class="keyword">else</span> <span class="keyword">if</span> ((i &amp; <span class="number">0xff</span>) == <span class="number">0xff</span>) &#123;</span><br><span class="line">            parkNanos(MICROSECONDS.toNanos(<span class="number">10</span>));</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">else</span> &#123;</span><br><span class="line">            <span class="comment">// 放弃时间片</span></span><br><span class="line">            yield();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">final</span> List&lt;Object&gt; threadLocalList = threadList.get();</span><br><span class="line">    <span class="keyword">if</span> (threadLocalList.size() &lt; <span class="number">50</span>) &#123;</span><br><span class="line">        <span class="comment">// 放到线程本地队列</span></span><br><span class="line">        threadLocalList.add(weakThreadLocals ? <span class="keyword">new</span> WeakReference&lt;&gt;(bagEntry) : bagEntry);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>一开始我也不明白作者为什么要每轮询 256 次阻塞 10 微妙（152-154），去 <code>issues</code> 搜索看到了<a href="https://github.com/brettwooldridge/HikariCP/issues/1305" target="_blank" rel="noopener">这个issue</a>，里面有这样一句话</p>
<blockquote>
<p>As there can be many threads in requite(), the occasional call to parkNanos() prevents CPU usage across many cores</p>
</blockquote>
<p>大意是：<code>requite()</code>这个方法有多个线程会调用，偶尔阻塞会防止 CPU 多个核心一直在这个方法轮转。</p>
<p>在并发比较大的情况下，有可能同时有多个线程释放连接，而获取连接的线程一直未得到调度，<code>yield()</code> 方法只是放弃时间片，线程进入就绪状态，有可能再次被调度。</p>
<h5 id="添加连接"><a href="#添加连接" class="headerlink" title="添加连接"></a>添加连接</h5><p>获取和释放连接的套路基本都清楚了，接下来看添加连接的操作吧，过程比获取和释放简单多了</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">add</span><span class="params">(<span class="keyword">final</span> T bagEntry)</span></span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (closed) &#123;</span><br><span class="line">     LOGGER.info(<span class="string">"ConcurrentBag has been closed, ignoring add()"</span>);</span><br><span class="line">     <span class="keyword">throw</span> <span class="keyword">new</span> IllegalStateException(<span class="string">"ConcurrentBag has been closed, ignoring add()"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 放到共享队列</span></span><br><span class="line">  sharedList.add(bagEntry);</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 当等待线程数量 &gt; 0 就自旋通知等待线程获取连接</span></span><br><span class="line">  <span class="keyword">while</span> (waiters.get() &gt; <span class="number">0</span> &amp;&amp; bagEntry.getState() == STATE_NOT_IN_USE &amp;&amp; !handoffQueue.offer(bagEntry)) &#123;</span><br><span class="line">     yield();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h5 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h5><p><code>Hikari</code> 的并发控制没有采取简单的加锁方式，而是采用 CAS 来实现线程间的资源竞争，减少了加锁的开销，用 <code>ThreadLocal</code> 缓存连接，最大限度的避免线程间的竞争 。</p>

      
    </div>

    

    
    
    

    

    
      
    
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/源码分析/" rel="tag"># 源码分析</a>
          
            <a href="/tags/HikariCP/" rel="tag"># HikariCP</a>
          
            <a href="/tags/并发/" rel="tag"># 并发</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/06/24/Spring MVC如何处理RequestMapping方法中的请求参数/" rel="next" title="Spring MVC如何处理RequestMapping方法中的请求参数">
                <i class="fa fa-chevron-left"></i> Spring MVC如何处理RequestMapping方法中的请求参数
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/03/26/HikariCP源码深度解读（二）/" rel="prev" title="HikariCP源码深度解读（二）">
                HikariCP源码深度解读（二） <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>


  </div>


          </div>
          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope="" itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/avatar.jpg" alt="isunimp">
            
              <p class="site-author-name" itemprop="name">isunimp</p>
              <p class="site-description motion-element" itemprop="description">涉猎广泛，不亦乐乎，不求甚解。</p>
          </div>

          
            <nav class="site-state motion-element">
              
                <div class="site-state-item site-state-posts">
                
                  <a href="/archives/">
                
                    <span class="site-state-item-count">3</span>
                    <span class="site-state-item-name">日志</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-categories">
                  <a href="/categories/index.html">
                    
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">2</span>
                    <span class="site-state-item-name">分类</span>
                  </a>
                </div>
              

              
                
                
                <div class="site-state-item site-state-tags">
                  <a href="/tags/index.html">
                    
                    
                      
                    
                      
                    
                      
                    
                      
                    
                      
                    
                    <span class="site-state-item-count">5</span>
                    <span class="site-state-item-name">标签</span>
                  </a>
                </div>
              
            </nav>
          

          

          
            <div class="links-of-author motion-element">
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="https://github.com/isunimp" title="GitHub &rarr; https://github.com/isunimp" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
                </span>
              
                <span class="links-of-author-item">
                  
                  
                    
                  
                  
                    
                  
                  <a href="mailto:ansheck@163.com" title="E-Mail &rarr; mailto:ansheck@163.com" rel="noopener" target="_blank"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
                </span>
              
            </div>
          

          

          
          

          
            
          
          

        </div>
      </div>

      
      <!--noindex-->
        <div class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-4"><a class="nav-link" href="#核心并发管理"><span class="nav-number">1.</span> <span class="nav-text">核心并发管理</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#获取连接"><span class="nav-number">1.1.</span> <span class="nav-text">获取连接</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#释放连接到连接池"><span class="nav-number">1.2.</span> <span class="nav-text">释放连接到连接池</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#添加连接"><span class="nav-number">1.3.</span> <span class="nav-text">添加连接</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#总结"><span class="nav-number">1.4.</span> <span class="nav-text">总结</span></a></li></ol></li></ol></div>
            

          </div>
        </div>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2017 – <span itemprop="copyrightYear">2019</span>
  <span class="with-love" id="animate">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">isunimp</span>

  

  
</div>


  <div class="powered-by">由 <a href="https://hexo.io" class="theme-link" rel="noopener" target="_blank">Hexo</a> 强力驱动 v3.8.0</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 – <a href="https://theme-next.org" class="theme-link" rel="noopener" target="_blank">NexT.Mist</a> v6.6.0</div>




        








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

    

    
  </div>

  

<script>
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>


























  
  
    <script src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  


  


  <script src="/js/src/utils.js?v=6.6.0"></script>

  <script src="/js/src/motion.js?v=6.6.0"></script>



  
  

  
  <script src="/js/src/scrollspy.js?v=6.6.0"></script>
<script src="/js/src/post-details.js?v=6.6.0"></script>



  


  <script src="/js/src/bootstrap.js?v=6.6.0"></script>



  



  











  





  

  

  

  

  

  
  

  

  

  

  

  

  

</body>
</html>
